import 'dart:convert';

import 'package:flutter_frame/generated/json/base/json_convert_content.dart';
import 'package:hive_flutter/hive_flutter.dart';

/// 本地存储
/// 1. 通过Hive进行存储
abstract class StorageUtil {

  static late final Box<dynamic> _hiveBox;

  // 初始化
  static Future<void> init() async {
    await Hive.initFlutter();
    _hiveBox = await Hive.openBox('storage');
  }

  /// 存储实体对象, 通过Json进行转换
  static Future<void> setJSON(String key, dynamic jsonVal) {
    final String jsonString = jsonEncode(jsonVal);
    return _hiveBox.put(key, jsonString);
  }

  /// 取出Json对象
  static dynamic getJSON(String key) {
    final String? jsonString = _hiveBox.get(key) as String?;
    return jsonString == null ? null : jsonDecode(jsonString);
  }

  /// 取出实体对象, 通过Json进行转换
  static T? getEntity<T>(String key) {
    final dynamic value = getJSON(key);
    return value == null ? null : JsonConvert.fromJsonAsT<T>(value);
  }

  static Future<void> setBool(String key, bool val) {
    return _hiveBox.put(key, val);
  }

  static bool? getBool(String key) {
    return _hiveBox.get(key) as bool?;
  }

  static int? getInt(String key) {
    return _hiveBox.get(key) as int?;
  }

  static Future<void> setInt(String key, int val) {
    return _hiveBox.put(key, val);
  }

  static Future<void> setString(String key, String val) {
    return _hiveBox.put(key, val);
  }

  static String? getString(String key) {
    return _hiveBox.get(key) as String?;
  }

  /// 删除
  static Future<void> remove(String key) {
    return _hiveBox.delete(key);
  }

  /// 删除多个
  static Future<void> removeAll(Iterable<String> keys) {
    return _hiveBox.deleteAll(keys);
  }
}
